<script lang="ts" setup>
import { ref } from 'vue'
import { routerReplace } from '@/utils/tools/index'
import { userLoginApi } from '@/api'
import store from '@/store'
import useRequest from '@/hooks/requestHooks'

const requestUtils = useRequest()
const formValue = ref({
  accountNumber: '',
  password: '',
})
const rules = ref({
  accountNumber: {
    required: true,
    message: '请输入账号',
    trigger: 'blur',
  },
  password: {
    required: true,
    message: '请输入密码',
    trigger: 'blur',
  },
})
const formRef = ref(null) as any
const loginLoading = ref(false)

const submitForm = async () => {
  formRef.value.validate(async (err: any) => {
    if (!err) {
      const res = await requestUtils.useLoadingRequest<{
        token: string
        id: string
        userName: string
      }>({
        axios: userLoginApi(formValue.value),
        loadings: loginLoading,
      })

      if (res.data?.data?.token) {
        window.localStorage.setItem('token', res.data.data.token)
        window.localStorage.setItem(
          'userInfo',
          JSON.stringify({
            userName: res.data.data.userName,
            id: res.data.data.id,
            userInfo: res.data.data,
          })
        )
      }

      if (res.data.code === 200) {
        store.commit('setIsOk', false)
        routerReplace({
          path: '/',
        })
      }
    }
  })
}
</script>

<template lang="pug">
div(class="bg")
  div(class="center")
    n-card(:content-style="{'paddingBottom': '0'}")
      n-form( :model="formValue" :rules="rules" label-align="left" label-placement="left" ref="formRef")
        n-form-item(label="账号：" path="accountNumber")
          n-input(v-model:value="formValue.accountNumber" placeholder="输入账号")
        n-form-item(label="密码：" path="password")
          n-input(v-model:value="formValue.password" placeholder="输入账号" type="password")
        n-form-item()
          div(style="display: flex;justify-content: space-evenly; width: 100%;")
            n-button(type="info" @click="submitForm" :loading="loginLoading") 登录   
            n-button() 注册
</template>

<style lang="scss" scoped>
.center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -30%);
  width: 400px;
}
.bg {
  background-image: url('../../assets/IMG_2176.JPG');
  background-size: cover;
  width: 100vw;
  height: 100vh;
}
</style>
